package com.pc.tas.learning.trace;

import com.pc.cloud.message.Listener;
import com.pc.cloud.services.SearchServices;
import com.pc.tas.learning.trace.index.TraceDocumentBuilder;

import java.util.ArrayList;
import java.util.Collection;


public class TraceListener implements Listener {
	public static final String QUEUE_NAME = "traceAnalyze";
	private static final Object MUTEX = new Object();	
	private SearchServices ss;
	private TraceService traceService;
	
	public void onMessage(String message) throws Exception {
		synchronized(MUTEX) {
			try {				
				Trace trace = new Trace(message);
				//TraceService ts = TraceService.getInstance();
				traceService.addUserTrace(trace);	
				
				//TODO It is better that the listener can receive more than one message at one time
				//because the Listener is less efficient by receiving messages one by one, 	
				
				//index trace
				Collection<Trace> traces = new ArrayList<Trace>();
				traces.add(trace);
				TraceDocumentBuilder builder = new TraceDocumentBuilder(traces);
				ss.index(builder);

			}catch(Exception e) {
				e.printStackTrace();
			} 			
		}		
	}

	public SearchServices getSs() {
		return ss;
	}

	public void setSs(SearchServices ss) {
		this.ss = ss;
	}

	public TraceService getTraceService() {
		return traceService;
	}

	public void setTraceService(TraceService traceService) {
		this.traceService = traceService;
	}
	
}
